package net.csdn.business.mirror.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.service.SuperServiceImpl;
import net.csdn.business.mirror.entity.bean.GithubToken;
import net.csdn.business.mirror.mapper.GithubTokenMapper;
import net.csdn.business.mirror.service.GithubTokenService;
import org.kohsuke.github.GHRateLimit;
import org.kohsuke.github.GitHub;
import org.kohsuke.github.GitHubBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Service
public class GithubTokenServiceImpl extends SuperServiceImpl<GithubTokenMapper, GithubToken> implements GithubTokenService {

    @Override
    public List<GithubToken> getAllToken() {
        return baseMapper.getAllToken();
    }

    @Override
    public void deleteAllToken() {
        baseMapper.clearData();
    }

    @Override
    public void saveToken(List<String> tokens) {
        if (CollectionUtils.isEmpty(tokens)) {
            return;
        }
        baseMapper.insertTokens(tokens);
    }

    @Override
    public void deleteToken(List<String> tokens) {
        if (CollectionUtils.isEmpty(tokens)) {
            return;
        }
        QueryWrapper<GithubToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(GithubToken::getToken, tokens);
        baseMapper.delete(queryWrapper);
    }

    @Override
    public GitHub getGithubClient() {
        List<GithubToken> tokens = getAllToken();
        return getGithubClient(tokens);
    }

    @Override
    public GitHub getGithubClient(List<GithubToken> tokens) {
        if (CollectionUtils.isEmpty(tokens)) {
            log.error("github token not exists");
            return null;
        }
        GitHub gitHub = null;
        String token = "";
        for (GithubToken githubToken : tokens) {
            try {
                token = githubToken.getToken();
                gitHub = new GitHubBuilder().withOAuthToken(token).build();
                GHRateLimit ghRateLimit = gitHub.getRateLimit();
                if (ghRateLimit.getCore().getRemaining() > 100) {
                    break;
                }
                gitHub = null;
            } catch (Exception e) {
                gitHub = null;
                log.error("get github client error token: {}", token, e);
            }
        }
        return gitHub;
    }
}
